#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/file.h>
#include <assert.h>
#include "headerhandler.h"
#include "logger.h"

#include "blankcap.h"

struct blankcon{
	char* url;
};

CAP_RETURN BlankCAP::ConnectCAP(void**, const char*, char**, int*){
	return CAP_NOCHANGE;
}
CAP_RETURN BlankCAP::RequestCAP(void**, char**, unsigned int *, HeaderHandlerInterface* hhi){
	hhi->DisplayHeaders();
	return CAP_NOCHANGE;
}

CAP_RETURN BlankCAP::PreRequestCAP(void** param1, HeaderHandlerInterface* hhi ){

	const char* req = hhi->GetRequestLine();
	const char* ip = hhi->GetHeader("X-Forwarded-For");
	int urlsize;
	blankcon* bcon;

	if(!*param1){
		*param1 = malloc(sizeof(blankcon));
		bcon=(blankcon*)*param1;
		bcon->url=0;
	}
	else
		bcon=(blankcon*)*param1;

	urlsize = strlen(ip)+1+strlen(req)+1;
	if(bcon->url)
		free(bcon->url);
	bcon->url=(char*)calloc(urlsize, sizeof(char));
	snprintf(bcon->url, urlsize, "%s %s", ip, req);

	//hhi->RemoveHeader("X-Forwarded-For");
	return CAP_NOCHANGE;
}

CAP_RETURN BlankCAP::ResponseCAP(void** param1, char**, unsigned int*, HeaderHandlerInterface* hhi){
	blankcon* bcon;
	if(*param1){
		bcon = (blankcon*)*param1;
		proxylog.ALog("%s - %s\n", bcon->url, hhi->GetRequestLine() );
	}
	return CAP_NOCHANGE;
}

CAP_RETURN BlankCAP::PreResponseCAP(void**, HeaderHandlerInterface* ){
	return CAP_NOCHANGE;
}

void BlankCAP::CloseCAP(void** param1){
	blankcon* bcon;
	if(*param1){
		bcon = (blankcon*)*param1;
		if(bcon->url)
			free(bcon->url);
		free(*param1);
		*param1=0;
	}
}

CAP_RETURN BlankCAP::InitCAP(){
	return CAP_NOCHANGE;
}

CAP_RETURN BlankCAP::ClearCAP(){
	return CAP_NOCHANGE;
}
